package com.fyb.basic.juc.semaphore;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author：MR.FANG
 * @name：Test
 * @Date：2025/7/2 下午2:52
 */
public class Test {

    public static void main(String[] args) {
        AtomicInteger ai = new AtomicInteger(1);
        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100,
                1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(100));

        executor.submit(new Thread(() -> {
            printNum(ai, a, b);
        }));
        executor.submit(new Thread(() -> {
            printNum(ai, b, c);
        }));
        executor.submit(new Thread(() -> {
            printNum(ai, c, a);
        }));
//        try (executor) {
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    private static void printNum(AtomicInteger ai, Semaphore cur, Semaphore next) {
        while (ai.get() <= 100) {
            try {
                cur.acquire();
                //必要--在多线程环境中，有可能一个线程已经通过了循环条件（ai.get() <= MAX_NUMBER）并且获取了信号量，而另一个线程（它已经在等待中）也通过了循环条件。如果没有额外的检查，两个线程可能在释放信号量之前都会打印超过上限的数字，导致输出不正确。
                if (ai.get() <= 100) {
                    System.out.println(ai.getAndIncrement());
                }
                next.release();
            } catch (InterruptedException e) {
                throw new RuntimeException();
            }
        }
    }
}
